package org.spring.springboot.tools;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class KeySecretUtil {

	/// <summary>
    /// ����
    /// </summary>
    /// <param name="sSrc">����ǰ����</param>
    /// <param name="sKey">16λ��Կ<</param>
    /// <returns></returns>
    public static String Encrypt(String sSrc, String sKey) {
  	  
  	      String result = null;
		      if (sKey ==null) {
		        System.out.print("KeyΪ��null");
		        return null;
		      }
		      // �ж�Key�Ƿ�Ϊ16λ
		      if (sKey.length() !=16) {
		       System.out.print("Key���Ȳ���16λ");
		       return null;
		      }
		      try {
		      byte[] raw = sKey.getBytes("utf-8");
		      SecretKeySpec skeySpec =new SecretKeySpec(raw, "AES");
		      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"�㷨/ģʽ/���뷽ʽ"
		      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		      
		      byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
		      
		      result = Base64.getEncoder().encodeToString(encrypted);
		      
		      }catch(Exception e) {
		    	  e.printStackTrace();
		      }
		return result;
	}
    
  /// <summary>
  /// ����
  /// </summary>
  /// <param name="sSrc">����</param>
  /// <param name="sKey">16λ��Կ</param>
  /// <returns></returns>
  public static String Decrypt(String sSrc, String sKey) throws Exception {
  try {
  // �ж�Key�Ƿ���ȷ
	  	         if (sKey ==null) {
                      System.out.print("KeyΪ��null");
                      return null;
                  }
  // �ж�Key�Ƿ�Ϊ16λ
	  			 if (sKey.length() !=16) {
                      System.out.print("Key���Ȳ���16λ");
                      return null;
                  }
	  			  byte[] raw = sKey.getBytes("utf-8");
                  SecretKeySpec skeySpec =new SecretKeySpec(raw, "AES");
                  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                  cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  				byte[] encrypted1 =Base64.getDecoder().decode(sSrc);//����base64����
  			     
  					byte[] original = cipher.doFinal(encrypted1);
                      String originalString =new String(original,"utf-8");
                      return originalString;
              } catch (Exception ex) {
                  System.out.println(ex.toString());
                  return null;
              }
        }
	
}
